<script setup lang="ts">
import { computed, ref } from 'vue';

import {
  BuildOutlined,
  FileOutlined,
  PlusOutlined,
  SafetyCertificateOutlined,
  UploadOutlined,
} from '@ant-design/icons-vue';
import { message } from 'ant-design-vue';

const showRegisterModal = ref(false);
const inheritanceModalVisible = ref(false);
const assetDetailModalVisible = ref(false);
const selectedAsset = ref<any>(null);

// IoT数据
const iotData = ref([
  { device: '温度传感器-1F', metric: '温度', value: 22.5, unit: '°C' },
  { device: '湿度传感器-1F', metric: '湿度', value: 45, unit: '%' },
  { device: '烟雾探测器-2F', metric: '烟雾浓度', value: 0, unit: 'ppm' },
  { device: '门禁系统', metric: '开门次数', value: 3, unit: '次/天' },
]);

// 资产文档
const assetDocuments = ref([
  {
    name: '房产证',
    ipfsHash: 'Qm...abc123',
    uploadTime: '2025-01-15 10:00:00',
  },
  {
    name: '土地使用权证',
    ipfsHash: 'Qm...def456',
    uploadTime: '2025-01-15 10:05:00',
  },
  {
    name: '资产评估报告',
    ipfsHash: 'Qm...ghi789',
    uploadTime: '2025-02-01 09:00:00',
  },
]);

// 继承执行记录
const inheritanceExecutions = ref([
  {
    id: 1,
    assetName: '南京祖宅',
    deceased: '朱元璋',
    beneficiary: '朱棣',
    executionDate: '2025-01-15',
    status: 'completed',
    txHash: '0x1234...5678',
  },
  {
    id: 2,
    assetName: '北京故宫',
    deceased: '朱棣',
    beneficiary: '朱高炽',
    executionDate: '2025-02-01',
    status: 'pending',
    txHash: '0xabcd...efgh',
  },
]);

// 继承执行记录表格列
const executionColumns = [
  {
    title: '资产名称',
    dataIndex: 'assetName',
    key: 'assetName',
  },
  {
    title: '逝者',
    dataIndex: 'deceased',
    key: 'deceased',
  },
  {
    title: '受益人',
    dataIndex: 'beneficiary',
    key: 'beneficiary',
  },
  {
    title: '执行日期',
    dataIndex: 'executionDate',
    key: 'executionDate',
  },
  {
    title: '状态',
    dataIndex: 'status',
    key: 'status',
  },
  {
    title: '交易哈希',
    dataIndex: 'txHash',
    key: 'txHash',
  },
];

// 资产数据
const assets = ref([
  {
    id: 1,
    tokenId: 'NFT-001',
    name: '南京祖宅',
    assetType: 'realEstate',
    location: '南京市秦淮区',
    value: 1500,
    owner: '朱元璋',
    txHash: '0x1234...5678',
    hasInheritanceRule: true,
    contractAddress: '0xabcd...efgh',
    nftImage: '/api/placeholder/300/200',
    description: '朱氏家族在南京的祖传宅院，具有重要的历史文化价值。',
  },
  {
    id: 2,
    tokenId: 'NFT-002',
    name: '明代青花瓷瓶',
    assetType: 'antique',
    location: '北京故宫博物院',
    value: 800,
    owner: '朱棣',
    txHash: '0x2345...6789',
    hasInheritanceRule: false,
    contractAddress: '',
    nftImage: '/api/placeholder/300/200',
    description: '明代永乐年间的青花瓷瓶，工艺精美，具有极高的艺术价值。',
  },
  {
    id: 3,
    tokenId: 'NFT-003',
    name: '家族信托基金',
    assetType: 'fund',
    location: '香港',
    value: 5000,
    owner: '朱高炽',
    txHash: '0x3456...7890',
    hasInheritanceRule: true,
    contractAddress: '0xbcde...fghi',
    nftImage: '/api/placeholder/300/200',
    description: '朱氏家族在香港设立的信托基金，用于家族财富传承。',
  },
  {
    id: 4,
    tokenId: 'NFT-004',
    name: '古树名木',
    assetType: 'natural',
    location: '苏州拙政园',
    value: 300,
    owner: '朱瞻基',
    txHash: '0x4567...8901',
    hasInheritanceRule: true,
    contractAddress: '0xcdef...ghij',
    nftImage: '/api/placeholder/300/200',
    description: '拙政园内的古银杏树，树龄超过500年，是重要的自然遗产。',
  },
]);

// 继承规则
const inheritanceRules = ref([
  {
    id: 1,
    assetId: 1,
    rule: '长子继承制',
    conditions: ['必须年满18岁', '必须完成家族教育'],
    beneficiaries: ['朱棣', '朱高炽'],
    percentages: [60, 40],
  },
  {
    id: 2,
    assetId: 3,
    rule: '均分继承制',
    conditions: ['必须年满21岁', '必须通过家族考核'],
    beneficiaries: ['朱棣', '朱高炽', '朱瞻基'],
    percentages: [33.33, 33.33, 33.34],
  },
]);

// 新增资产表单
const newAsset = ref({
  name: '',
  assetType: 'realEstate',
  location: '',
  value: 0,
  description: '',
});

// 继承规则表单
const newInheritanceRule = ref({
  assetId: null,
  rule: '',
  conditions: [''],
  beneficiaries: [''],
  percentages: [100],
});

// 需要公证处签名
const requireNotary = ref(false);

// 计算属性
const totalValue = computed(() => {
  return assets.value.reduce((sum, asset) => sum + asset.value, 0);
});

const assetTypeOptions = [
  { label: '房产', value: 'realEstate' },
  { label: '古董', value: 'antique' },
  { label: '基金', value: 'fund' },
  { label: '自然资源', value: 'natural' },
];

const getAssetColor = (type: string) => {
  const colors = {
    realEstate: 'blue',
    antique: 'gold',
    fund: 'green',
    natural: 'lime',
  };
  return colors[type as keyof typeof colors] || 'default';
};

const getAssetTypeText = (type: string) => {
  const texts = {
    realEstate: '房产',
    antique: '古董',
    fund: '基金',
    natural: '自然资源',
  };
  return texts[type as keyof typeof texts] || type;
};

// 方法
const registerAsset = () => {
  if (
    !newAsset.value.name ||
    !newAsset.value.location ||
    !newAsset.value.value
  ) {
    message.error('请填写完整信息');
    return;
  }

  const asset = {
    id: assets.value.length + 1,
    tokenId: `NFT-${String(assets.value.length + 1).padStart(3, '0')}`,
    ...newAsset.value,
    owner: '当前用户',
    txHash: `0x${Math.random().toString(16).slice(2, 10)}...`,
    hasInheritanceRule: false,
    contractAddress: '',
    nftImage: '/api/placeholder/300/200',
  };

  assets.value.push(asset);
  message.success('资产注册成功！');
  showRegisterModal.value = false;

  // 重置表单
  newAsset.value = {
    name: '',
    assetType: 'realEstate',
    location: '',
    value: 0,
    description: '',
  };
};

const showAssetDetail = (asset: any) => {
  selectedAsset.value = asset;
  assetDetailModalVisible.value = true;
};

const createInheritanceRule = () => {
  if (!newInheritanceRule.value.assetId || !newInheritanceRule.value.rule) {
    message.error('请填写完整信息');
    return;
  }

  const rule = {
    id: inheritanceRules.value.length + 1,
    ...newInheritanceRule.value,
  };

  inheritanceRules.value.push(rule);
  message.success('继承规则创建成功！');
  inheritanceModalVisible.value = false;

  // 重置表单
  newInheritanceRule.value = {
    assetId: null,
    rule: '',
    conditions: [''],
    beneficiaries: [''],
    percentages: [100],
  };
};

const executeInheritance = (asset: any) => {
  message.success(`开始执行 ${asset.name} 的继承流程`);
};

const downloadAssetDocuments = (asset: any) => {
  message.success(`下载 ${asset.name} 的相关文档`);
};

const viewBIM = (asset: any) => {
  message.success(`查看 ${asset.name} 的BIM数字孪生模型`);
};

const viewIoTData = (asset: any) => {
  message.success(`查看 ${asset.name} 的IoT实时数据`);
};
</script>

<template>
  <div class="wealth-management">
    <a-card>
      <template #title>
        <div
          style="
            display: flex;
            align-items: center;
            justify-content: space-between;
          "
        >
          <span>💰 家族财富与RWA管理</span>
          <a-button type="primary" @click="showRegisterModal = true">
            <PlusOutlined /> 注册资产
          </a-button>
        </div>
      </template>

      <!-- 财富概览 -->
      <a-row :gutter="16" style="margin-bottom: 24px">
        <a-col :span="6">
          <a-statistic title="总资产价值" :value="totalValue" suffix="万" />
        </a-col>
        <a-col :span="6">
          <a-statistic title="资产数量" :value="assets.length" suffix="个" />
        </a-col>
        <a-col :span="6">
          <a-statistic title="已上链资产" :value="assets.length" suffix="个" />
        </a-col>
        <a-col :span="6">
          <a-statistic
            title="继承规则"
            :value="inheritanceRules.length"
            suffix="条"
          />
        </a-col>
      </a-row>

      <!-- 资产列表 -->
      <a-row :gutter="16">
        <a-col
          v-for="asset in assets"
          :key="asset.id"
          :span="8"
          style="margin-bottom: 16px"
        >
          <a-card class="asset-card" hoverable @click="showAssetDetail(asset)">
            <template #cover>
              <img
                :src="asset.nftImage"
                :alt="asset.name"
                class="nft-preview"
              />
            </template>
            <a-card-meta>
              <template #title>
                <div
                  style="
                    display: flex;
                    align-items: center;
                    justify-content: space-between;
                  "
                >
                  <span>{{ asset.name }}</span>
                  <a-tag :color="getAssetColor(asset.assetType)">
                    {{ getAssetTypeText(asset.assetType) }}
                  </a-tag>
                </div>
              </template>
              <template #description>
                <div>位置：{{ asset.location }}</div>
                <div>价值：¥{{ asset.value.toLocaleString() }}万</div>
                <div>所有者：{{ asset.owner }}</div>
                <div v-if="asset.hasInheritanceRule">
                  <a-tag color="green">已配置继承规则</a-tag>
                </div>
              </template>
            </a-card-meta>
            <template #actions>
              <a @click.stop="viewBIM(asset)"> <BuildOutlined /> BIM模型 </a>
              <a @click.stop="viewIoTData(asset)">
                <SafetyCertificateOutlined /> IoT数据
              </a>
              <a @click.stop="downloadAssetDocuments(asset)">
                <FileOutlined /> 文档
              </a>
            </template>
          </a-card>
        </a-col>
      </a-row>

      <!-- 继承规则 -->
      <a-card title="📋 继承规则管理" style="margin-top: 16px">
        <a-button
          type="dashed"
          block
          @click="inheritanceModalVisible = true"
          style="margin-bottom: 16px"
        >
          <PlusOutlined /> 创建继承规则
        </a-button>

        <a-list :data-source="inheritanceRules">
          <template #renderItem="{ item }">
            <a-list-item>
              <a-list-item-meta>
                <template #title>
                  {{ item.rule }}
                </template>
                <template #description>
                  <div>
                    适用资产：{{
                      assets.find((a) => a.id === item.assetId)?.name
                    }}
                  </div>
                  <div>受益人：{{ item.beneficiaries.join(', ') }}</div>
                  <div>分配比例：{{ item.percentages.join('%, ') }}%</div>
                </template>
              </a-list-item-meta>
              <template #actions>
                <a
                  @click="
                    executeInheritance(
                      assets.find((a) => a.id === item.assetId),
                    )
                  "
                >
                  执行继承
                </a>
                <a>编辑</a>
                <a danger>删除</a>
              </template>
            </a-list-item>
          </template>
        </a-list>
      </a-card>
    </a-card>

    <!-- 资产注册Modal -->
    <a-modal
      v-model:open="showRegisterModal"
      title="📝 注册新资产"
      @ok="registerAsset"
      @cancel="showRegisterModal = false"
    >
      <a-form layout="vertical">
        <a-form-item label="资产名称" required>
          <a-input v-model:value="newAsset.name" placeholder="请输入资产名称" />
        </a-form-item>
        <a-form-item label="资产类型" required>
          <a-select v-model:value="newAsset.assetType">
            <a-select-option
              v-for="option in assetTypeOptions"
              :key="option.value"
              :value="option.value"
            >
              {{ option.label }}
            </a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="位置" required>
          <a-input
            v-model:value="newAsset.location"
            placeholder="请输入资产位置"
          />
        </a-form-item>
        <a-form-item label="评估价值（万元）" required>
          <a-input-number
            v-model:value="newAsset.value"
            :min="0"
            style="width: 100%"
            placeholder="请输入评估价值"
          />
        </a-form-item>
        <a-form-item label="描述">
          <a-textarea
            v-model:value="newAsset.description"
            placeholder="请输入资产描述"
            :rows="3"
          />
        </a-form-item>
        <a-form-item label="上传相关文件">
          <a-upload
            :file-list="[]"
            :before-upload="() => false"
            accept=".pdf,.jpg,.png,.doc,.docx"
          >
            <a-button> <UploadOutlined /> 选择文件 </a-button>
          </a-upload>
          <div class="upload-tip">文件将上传至IPFS，生成哈希存证</div>
        </a-form-item>
      </a-form>
    </a-modal>

    <!-- 资产详情Modal -->
    <a-modal
      v-model:open="assetDetailModalVisible"
      :title="`📋 资产详情 - ${selectedAsset?.name}`"
      width="1000px"
      :footer="null"
    >
      <a-tabs v-if="selectedAsset">
        <a-tab-pane key="basic" tab="基本信息">
          <a-descriptions bordered :column="2">
            <a-descriptions-item label="NFT ID">
              {{ selectedAsset.tokenId }}
            </a-descriptions-item>
            <a-descriptions-item label="资产类型">
              <a-tag :color="getAssetColor(selectedAsset.assetType)">
                {{ getAssetTypeText(selectedAsset.assetType) }}
              </a-tag>
            </a-descriptions-item>
            <a-descriptions-item label="资产名称">
              {{ selectedAsset.name }}
            </a-descriptions-item>
            <a-descriptions-item label="位置">
              {{ selectedAsset.location }}
            </a-descriptions-item>
            <a-descriptions-item label="评估价值">
              ¥{{ selectedAsset.value.toLocaleString() }}万
            </a-descriptions-item>
            <a-descriptions-item label="上链时间">
              2025-01-15 10:00:00
            </a-descriptions-item>
            <a-descriptions-item label="交易哈希">
              {{ selectedAsset.txHash }}
            </a-descriptions-item>
            <a-descriptions-item label="合约地址">
              {{ selectedAsset.contractAddress || '未配置' }}
            </a-descriptions-item>
            <a-descriptions-item label="描述" :span="2">
              {{ selectedAsset.description }}
            </a-descriptions-item>
          </a-descriptions>
        </a-tab-pane>

        <a-tab-pane key="documents" tab="相关文档">
          <a-list :data-source="assetDocuments" size="small">
            <template #renderItem="{ item }">
              <a-list-item>
                <a-list-item-meta>
                  <template #title>
                    {{ item.name }}
                  </template>
                  <template #description>
                    <div>IPFS哈希：{{ item.ipfsHash }}</div>
                    <div>上传时间：{{ item.uploadTime }}</div>
                  </template>
                </a-list-item-meta>
              </a-list-item>
            </template>
          </a-list>
        </a-tab-pane>

        <a-tab-pane key="bim" tab="BIM数字孪生">
          <div class="bim-viewer">
            <div
              style="
                display: flex;
                align-items: center;
                justify-content: center;
                height: 100%;
                color: #666;
              "
            >
              BIM 3D模型加载中...
            </div>
          </div>
        </a-tab-pane>

        <a-tab-pane key="iot" tab="IoT实时数据">
          <div class="iot-dashboard">
            <div v-for="data in iotData" :key="data.device" class="metric-card">
              <h4>{{ data.device }}</h4>
              <a-statistic
                :value="data.value"
                :suffix="data.unit"
                :value-style="{ color: '#1890ff' }"
              />
              <div>{{ data.metric }}</div>
            </div>
          </div>
        </a-tab-pane>

        <a-tab-pane key="inheritance" tab="继承规则">
          <div v-if="selectedAsset.hasInheritanceRule">
            <a-alert
              message="已配置继承规则"
              type="success"
              style="margin-bottom: 16px"
            />
            <a-descriptions bordered>
              <a-descriptions-item label="继承规则">
                长子继承制
              </a-descriptions-item>
              <a-descriptions-item label="继承条件">
                <ul>
                  <li>必须年满18岁</li>
                  <li>必须完成家族教育</li>
                </ul>
              </a-descriptions-item>
              <a-descriptions-item label="受益人">
                朱棣 (60%), 朱高炽 (40%)
              </a-descriptions-item>
            </a-descriptions>
          </div>
          <div v-else>
            <a-empty description="暂未配置继承规则">
              <a-button type="primary" @click="inheritanceModalVisible = true">
                创建继承规则
              </a-button>
            </a-empty>
          </div>
        </a-tab-pane>

        <a-tab-pane key="history" tab="操作历史">
          <a-timeline>
            <a-timeline-item color="green">
              <p>2025-01-15 10:00:00</p>
              <p>资产登记上链</p>
              <p>交易哈希：{{ selectedAsset.txHash }}</p>
            </a-timeline-item>
            <a-timeline-item
              color="blue"
              v-if="selectedAsset.hasInheritanceRule"
            >
              <p>2025-01-16 14:30:00</p>
              <p>配置继承规则</p>
              <p>合约地址：0x1234...5678</p>
            </a-timeline-item>
            <a-timeline-item color="orange">
              <p>2025-02-01 09:00:00</p>
              <p>更新资产评估</p>
              <p>新价值：¥{{ selectedAsset.value.toLocaleString() }}万</p>
            </a-timeline-item>
          </a-timeline>
        </a-tab-pane>
      </a-tabs>
    </a-modal>

    <!-- 继承执行记录 -->
    <a-card title="📜 继承执行记录" style="margin-top: 16px">
      <a-table
        :data-source="inheritanceExecutions"
        :columns="executionColumns"
        size="small"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'status'">
            <a-tag
              :color="
                record.status === 'completed'
                  ? 'green'
                  : record.status === 'pending'
                    ? 'orange'
                    : 'blue'
              "
            >
              {{
                record.status === 'completed'
                  ? '已完成'
                  : record.status === 'pending'
                    ? '待处理'
                    : '进行中'
              }}
            </a-tag>
          </template>
        </template>
      </a-table>
    </a-card>

    <!-- 创建继承规则Modal -->
    <a-modal
      v-model:open="inheritanceModalVisible"
      title="📋 创建继承规则"
      @ok="createInheritanceRule"
      @cancel="inheritanceModalVisible = false"
    >
      <a-form layout="vertical">
        <a-form-item label="适用资产" required>
          <a-select
            v-model:value="newInheritanceRule.assetId"
            placeholder="请选择资产"
          >
            <a-select-option
              v-for="asset in assets"
              :key="asset.id"
              :value="asset.id"
            >
              {{ asset.name }}
            </a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="继承规则" required>
          <a-input
            v-model:value="newInheritanceRule.rule"
            placeholder="请输入继承规则名称"
          />
        </a-form-item>
        <a-form-item label="继承条件">
          <a-input
            v-for="(condition, index) in newInheritanceRule.conditions"
            :key="index"
            v-model:value="newInheritanceRule.conditions[index]"
            placeholder="请输入继承条件"
            style="margin-bottom: 8px"
          />
          <a-button
            type="dashed"
            @click="newInheritanceRule.conditions.push('')"
            style="width: 100%"
          >
            <PlusOutlined /> 添加条件
          </a-button>
        </a-form-item>
        <a-form-item label="受益人">
          <a-input
            v-for="(beneficiary, index) in newInheritanceRule.beneficiaries"
            :key="index"
            v-model:value="newInheritanceRule.beneficiaries[index]"
            placeholder="请输入受益人姓名"
            style="margin-bottom: 8px"
          />
          <a-button
            type="dashed"
            @click="newInheritanceRule.beneficiaries.push('')"
            style="width: 100%"
          >
            <PlusOutlined /> 添加受益人
          </a-button>
        </a-form-item>
        <a-form-item label="分配比例（%）">
          <a-input-number
            v-for="(percentage, index) in newInheritanceRule.percentages"
            :key="index"
            v-model:value="newInheritanceRule.percentages[index]"
            :min="0"
            :max="100"
            placeholder="分配比例"
            style="width: 100%; margin-bottom: 8px"
          />
        </a-form-item>
        <a-form-item label="公证处签名（可选）">
          <a-switch v-model:checked="requireNotary" />
          <span style="margin-left: 8px">需要公证处签名确认</span>
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<style scoped lang="scss">
.wealth-management {
  .upload-tip {
    margin-top: 8px;
    font-size: 12px;
    color: #666;
  }

  .asset-card {
    cursor: pointer;
    transition: all 0.3s;

    &:hover {
      box-shadow: 0 4px 12px rgb(0 0 0 / 15%);
    }
  }

  .asset-grid {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
    gap: 16px;
  }

  .inheritance-rule {
    padding: 12px;
    margin: 8px 0;
    background: #f6ffed;
    border: 1px solid #b7eb8f;
    border-radius: 6px;
  }

  .nft-preview {
    width: 100%;
    height: 200px;
    object-fit: cover;
    border-radius: 6px;
  }

  .bim-viewer {
    width: 100%;
    height: 400px;
    border: 1px solid #d9d9d9;
    border-radius: 6px;
  }

  .iot-dashboard {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
    gap: 16px;
  }

  .metric-card {
    padding: 16px;
    text-align: center;
    background: #fafafa;
    border-radius: 6px;
  }
}
</style>
